//
//  AppDelegate.swift
//  Employee
//
//  Created by swordjoy on 2017/3/9.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import UserNotifications
import AdSupport
import SwiftyJSON

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    UserRequest.shared.versionApplication()
    UserRequest.shared.setPushAlias()
    // 极光推送
    registerJSPush(launchOptions: launchOptions)
    // IQ键盘管理
    IQConfig()
    // 百度统计
    baiduMobStatConfig()
    
    window = UIWindow(frame: UIScreen.main.bounds)
    window?.backgroundColor = UIColor.white
    window?.rootViewController = SJBaseNavigationC(rootViewController: HomeVC())
    window?.makeKeyAndVisible()
    
    // 位置不能改变
    appStartWithNotice(launchOptions: launchOptions)
    
    return true
  }


    // APP进入后台
    func applicationDidEnterBackground(_ application: UIApplication) {
        // 环信
    }

    // APP即将进入前台
    func applicationWillEnterForeground(_ application: UIApplication) {
        // 环信
        JPUSHService.resetBadge()
        application.applicationIconBadgeNumber = 0
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        
        
    }

    func applicationWillTerminate(_ application: UIApplication) { }
}


// MARK: - JSPush

extension AppDelegate: JPUSHRegisterDelegate {
  
    /// app关闭后,点击通知进入
    fileprivate func appStartWithNotice(launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
        
        if #available(iOS 10.0, *) {
            return
        }
        
        if let temp = launchOptions {
            let notification = temp[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
            guard let temp = notification else { return }
            guard let keys = temp.allKeys as? [String] else { return }
            
            if keys.contains("messageType") {
                let string = temp.object(forKey: "messageType") as! String
                // 如果来自工单和巡检,不做处理进入首页
                if "WorkOrder" == string || "InspectionTask" == string {
                    let t = DispatchTime.now() + 0.5
                    DispatchQueue.main.asyncAfter(deadline: t) {
                        self.pushDetail(json: JSON(temp))
                    }
                }
            }
        }
    }
    
  
  @available(iOS 10.0, *)
  func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
    let info = response.notification.request.content.userInfo
    let messageType = (info["messageType"] as? String) ?? ""
    
    switch UIApplication.shared.applicationState {
    case .background: break
    case .active: break
    case .inactive:
        if "WorkOrder" == messageType || "InspectionTask" == messageType {
            let t = DispatchTime.now() + 0.5
            DispatchQueue.main.asyncAfter(deadline: t) {
                self.pushDetail(json: JSON(info))
            }
        }
        break
        
    }
    
    UIApplication.shared.applicationIconBadgeNumber = 0
    completionHandler()
    SJApp.log("didReceive")
  }
  @available(iOS 10.0, *)
  func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
    let info = notification.request.content.userInfo
    SJApp.log(info["messageType"] ?? "")
    SJApp.log("willPresent")
  }

  
    func registerJSPush(launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
        let entity = JPUSHRegisterEntity()
        entity.types = Int(JPAuthorizationOptions.alert.rawValue | JPAuthorizationOptions.badge.rawValue | JPAuthorizationOptions.sound.rawValue)
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        JPUSHService.setup(withOption: launchOptions, appKey: GlobalConfig.JSPush_Key, channel: "App Store", apsForProduction: SJToolkitConfig.serviceType ? false : true)
        UIApplication.shared.applicationIconBadgeNumber = 0

        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(didReceiveMessageNotification(_:)), name: NSNotification.Name.jpfNetworkDidReceiveMessage, object: nil)
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(didLogin), name: NSNotification.Name.jpfNetworkDidLogin, object: nil)
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(didRegister), name: NSNotification.Name.jpfNetworkDidRegister, object: nil)
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(isConnecting), name: NSNotification.Name.jpfNetworkIsConnecting, object: nil)
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(isConnecting), name: NSNotification.Name.jpfServiceError, object: nil)
        GlobalConfig.notificationCenter.addObserver(self, selector: #selector(failedRegister), name: NSNotification.Name.jpfNetworkFailedRegister, object: nil)
        JPUSHService.setDebugMode()
    }
  
  @objc func didReceiveMessageNotification(_ notification: Notification) {
    SJApp.log("didReceiveMessageNotification" + "\(JPUSHService.registrationID())")
    
    
  }
    
    @objc func errorOccur() {
        SJApp.log("errorOccur:" + "\(JPUSHService.registrationID())")
    }
    
    @objc func failedRegister() {
        SJApp.log("failedRegister:" + "\(JPUSHService.registrationID())")
    }
    
    @objc func isConnecting() {
        SJApp.log("isConnecting" + "\(JPUSHService.registrationID())")
    }
    @objc func didSetup() {
        SJApp.log("didSetup" + "\(JPUSHService.registrationID())")
    }
    @objc func didRegister() {
        SJApp.log("didRegister" + "\(JPUSHService.registrationID())")
    }
    @objc func didLogin() {
        if Account.isLogin && !Account.isSetPushAlias { UserRequest.shared.setPushAlias() }
    }
}

// MARK: - UNUserNotificationCenterDelegate iOS 10 和通知推送相关
extension AppDelegate: UNUserNotificationCenterDelegate {
  
    func pushDetail(json:JSON) {
        if !Account.isLogin {
            return
        }
        let model = WorkOrder(json:json)
        let root = UIApplication.shared.keyWindow?.rootViewController
        let vc = OrderDetailBaseVC()
        vc.orderId = model.id
        vc.parentVC = root
        vc.orderStatus = OrderHelper.getType(order: model)
        
        if root is UINavigationController {
            let nav = root as? UINavigationController
            nav?.pushViewController(vc, animated: true)
        } else {
            root?.navigationController?.pushViewController(vc, animated: true)
        }
    }
  // 推送的设备token
  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // 将token传送给环信
    JPUSHService.registerDeviceToken(deviceToken)
  }
  
  func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    SJApp.log("注册deviceToken失败")
  }
  
  
  // 接收到本地通知
  func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
    
  }
  
  // 接收到远程通知
  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {

    JPUSHService.handleRemoteNotification(userInfo)
    application.applicationIconBadgeNumber = 0
  
    let messageType = (userInfo["messageType"] as? String) ?? ""
    
    switch application.applicationState {
    case .active: break
    case .background: break
    case .inactive:
        if "WorkOrder" == messageType || "InspectionTask" == messageType {
            pushDetail(json: JSON(userInfo))
        }
        break
        
    }
  }
  
  @available(iOS 10.0, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    
    SJApp.log("userNotificationCenter didReceive")
    SJApp.log(response.notification.request.content.userInfo)
    completionHandler()
  }
  
  @available(iOS 10.0, *)
  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    
  }
  
  
}

// MARK: - IQKeyboardManager

extension AppDelegate {
  
  fileprivate func IQConfig() {
    IQKeyboardManager.sharedManager().enable = true
    IQKeyboardManager.sharedManager().toolbarTintColor = GlobalConfig.BGSkyBlueColor
    IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText = "完成"
    IQKeyboardManager.sharedManager().toolbarBarTintColor = GlobalConfig.BGWhiteColor
    IQKeyboardManager.sharedManager().shouldShowToolbarPlaceholder = false
  }
  
}

// MARK: - 百度统计

extension AppDelegate {
  
  fileprivate func baiduMobStatConfig() {
    #if RELEASE
//        BaiduMobStat.default().start(withAppId: "c0e255bae0")
//        BaiduMobStat.default().enableDebugOn = false
    #endif
  }
  
}

